using System.Windows;

namespace PrismNavigationFramework.MVVM
{
    public interface IViewInitializationService
    {
        object InitializeView(object view, string regionName, string rawInitializationData);
        object InitializeView(object view, ViewInitializationData initializationData);
    }

    public class ViewInitializationService : IViewInitializationService
    {
        private readonly IViewInitializationDataParsingService _viewInitializationDataParsingService;

        public ViewInitializationService(IViewInitializationDataParsingService viewInitializationDataParsingService)
        {
            _viewInitializationDataParsingService = viewInitializationDataParsingService;
        }

        public object InitializeView(object view, string regionName, string rawInitializationData)
        {
            var initData = this._viewInitializationDataParsingService.Parse(rawInitializationData);
            initData.RegionName = regionName;
            return this.InitializeView(view, initData);
        }

        public object InitializeView(object view, ViewInitializationData initializationData)
        {
            var viewAsFrameworkElement = view as FrameworkElement;
            if (viewAsFrameworkElement != null)
            {
                var viewModelAcceptsInitializationData = viewAsFrameworkElement.DataContext as IAcceptInitializationData;
                if (viewModelAcceptsInitializationData != null)
                {
                    viewModelAcceptsInitializationData.Initialize(initializationData);
                }
            }

            return view;           
        }
    }
}